package com.test4.controller;

import com.test4.entity.Book;
import com.test4.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class bookController {
    @Resource
    private BookService bookService;
//    查找所有图书
    @GetMapping("/list")
    public ModelAndView findAllBook(){
        List<Book> books=bookService.findAllBooks();
        ModelAndView mv=new ModelAndView();
        mv.addObject("books",books);
        mv.setViewName("books");
        return mv;
    }
//    查找指定编号的图书
    @GetMapping("book/{id}")
    public ModelAndView findStudentById(@PathVariable("id") int id){
        Book book=bookService.findBookById(id);
        ModelAndView mv=new ModelAndView();
        mv.addObject("book",book);
        mv.setViewName("bookdetail");
        return mv;
    }
//    添加新书
    @PostMapping("/addBook")
    public ModelAndView addBook(Book book){
        bookService.addBook(book);
        ModelAndView mv=new ModelAndView();
//        添加成功后跳转主页
        mv.setViewName("redirect:/books");
        return mv;
    }
//    添加新书视图界面
    @GetMapping("/addBook")
    public String addBook(){
        return "addBook";
    }
//    根据编号删除图书
    @GetMapping("/deleteBook/{id}")
    public ModelAndView deleteBook(@PathVariable("id") int id){
        bookService.deleteBook(id);
        ModelAndView mv=new ModelAndView();
//        删除成功后跳转到主页
        mv.setViewName("redirect:/books");
        return mv;
    }
//    修改图书视图界面
    @GetMapping("/toupdatebook/{id}")
    public ModelAndView toUpdateBook(@PathVariable("id") int id){
        Book book=new Book();
        ModelAndView mv=new ModelAndView();
        mv.addObject("book",book);
        mv.setViewName("updateBook");
        return mv;
    }
//    修改图书动作
    @PostMapping("/updateBook")
    public ModelAndView updateBook(Book book){
        bookService.updateBook(book);
        ModelAndView mv=new ModelAndView();
//        修改成功后跳转主页
        mv.setViewName("redirect:/books");
        return mv;
    }
}
